#!/bin/bash -x
set -x
ProgName=$(basename $0)
BaseDir=$(dirname $(readlink -f "$0"))
LocalAppHome=$(dirname $BaseDir)
SYSOM_INIT_LOG=$LOG_HOME/sysom_init.log

####################################################################################################################
# Helper functions
####################################################################################################################
yellow() {
    printf '\33[1;33m%b\n\33[0m' "$1"
}

red() {
    printf '\33[1;31m%b\n\33[0m' "$1"
}

green() {
    printf '\33[1;32m%b\n\33[0m' "$1"
}

do_init_microservices() {
    target=$1
    targets=(${target//,/ })
    for target in ${targets[*]}; do
        for service in $(ls ${MICROSERVICE_HOME} | grep ${target}); do
            service_dir=${MICROSERVICE_HOME}/${service}
            service_deploy_script_dir=${MICROSERVICE_SCRIPT_HOME}/${service}

            ################################################################################################
            # Service conf initial
            ################################################################################################
            pushd ${service_dir}
            # update microservice common.py, replace {BASE_DIR.parent.parent}/conf/config.yml to ${SYSOM_CONF}
            if [ -f "${service_dir}/conf/common.py" ]; then
                sed -i "s;{BASE_DIR.parent.parent}/conf/config.yml;/etc/sysom/config.yml;g" ${service_dir}/conf/common.py
            fi
            # update fastapi based microservice alembic/env.py, replace {BASE_DIR.parent.parent}/conf/config.yml to ${SYSOM_CONF}
            if [ -f "${service_dir}/alembic/env.py" ]; then
                sed -i "s;{BASE_DIR.parent.parent}/conf/config.yml;/etc/sysom/config.yml;g" ${service_dir}/alembic/env.py
            fi
            # update microservice gunicorn.py replace /var/log/sysom to ${LOG_HOME}
            if [ -f "${service_dir}/conf/gunicorn.py" ]; then
                sed -i "s;/var/log/sysom;${LOG_HOME};g" ${service_dir}/conf/gunicorn.py
            fi
            popd

            ################################################################################################
            # Perform service initial script
            ################################################################################################

            pushd ${service_deploy_script_dir}
            # update *.ini replace /var/log/sysom to ${LOG_HOME}
            for ini_conf in $(ls sysom-*.ini); do
                sed -i "s;/var/log/sysom;${LOG_HOME};g" ${service_deploy_script_dir}/${ini_conf}
            done

            green "$service_deploy_script_dir initialing..................................."
            if [ ! -f "${service_deploy_script_dir}/init.sh" ]; then
                popd
                continue
            fi
            bash -x ${service_deploy_script_dir}/init.sh
            if [ $? -ne 0 ]; then
                red "$service_deploy_script_dir initial fail, please check..................................."
                red "sysom init failed, exit 1"
                exit 1
            fi
            popd
        done
    done
}

do_init_environment() {
    target=$1
    targets=(${target//,/ })
    for target in ${targets[*]}; do
        for env in $(ls ${ENVIRONMENT_HOME} | grep ${target}); do

            target_dir=${ENVIRONMENT_HOME}/${env}
            if [ ! -d "${target_dir}" ] || [ ! -f "${target_dir}/init.sh" ]; then
                continue
            fi

            pushd ${target_dir}

            green "$target_dir initialing..................................."
            bash -x ${target_dir}/init.sh
            if [ $? -ne 0 ]; then
                red "$target_dir initial fail, please check..................................."
                red "sysom init failed, exit 1"
                exit 1
            fi
            popd
        done

    done
}

do_init_deps() {
    target=$1
    targets=(${target//,/ })
    for target in ${targets[*]}; do
        for dep in $(ls ${DEPS_HOME} | grep ${target}); do

            target_dir=${DEPS_HOME}/${dep}
            if [ ! -d "${target_dir}" ] || [ ! -f "${target_dir}/init.sh" ]; then
                continue
            fi

            pushd ${target_dir}

            green "$target_dir initialing..................................."
            bash -x ${target_dir}/init.sh
            if [ $? -ne 0 ]; then
                red "$target_dir initial fail, please check..................................."
                red "sysom init failed, exit 1"
                exit 1
            fi
            popd
        done

    done
}

ensure_supervisor_active() {
    # 1. First ensure supervisor installed
    rpm -q --quiet supervisor || yum install -y supervisor

    # 2. Then ensure supervisord is active
    result=$(systemctl is-active supervisord)
    if [ "$result" != "active" ]; then
        systemctl enable supervisord
        systemctl start supervisord
    fi
}

####################################################################################################################
# Subcommands
####################################################################################################################

sub_help() {
    echo "Usage: $ProgName <subcommand> [options]"
    echo "Subcommands:"
    echo "    all     Init all modules"
    echo "    env   [ALL | <base_env_name>]        Init all enviroment or specific enviroment"
    echo "          Example: $ProgName env env"
    echo "          Example: $ProgName env sdk"
    echo "    deps  [ALL | <deps_name>]            Init all deps or specific dep"
    echo "          Example: $ProgName dep mysql"
    echo "          Example: $ProgName dep grafana"
    echo "    ms    [ALL | <service_name>]         Init all microservices or specific microservice"
    echo "          Example: $ProgName ms sysom_diagnosis"
    echo ""
    echo "For help with each subcommand run:"
    echo "$ProgName <subcommand> -h|--help"
    echo ""
}

sub_ALL() {
    sub_deps ALL
    sub_env ALL
    sub_ms ALL
    sub_web
}

sub_all() {
    sub_ALL
}

sub_env() {
    sub_environment $@
}

# -> env + local_services
sub_environment() {
    target=$1
    if [ "$target" == "ALL" ]; then
        do_init_environment $DEPLOY_ENV_LIST
    else
        # Deploy specific microservices
        do_init_environment $target
    fi
}

sub_ms() {
    sub_microservice $@
}

sub_server() {
    sub_microservice $@
}

# All microservices
sub_microservice() {
    target=$1
    if [ "$target" == "ALL" ]; then
        do_init_microservices $DEPLOY_SERVER_LIST
    else
        # Deploy specific microservices
        do_init_microservices $target
    fi
}

sub_deps() {
    target=$1
    if [ "$target" == "ALL" ]; then
        do_init_deps $DEPLOY_DEPS_LIST
    else
        # Deploy specific microservices
        do_init_deps $target
    fi
}

# Deploy web
sub_web() {
    echo ""
}

check_config_exist() {
    if [ ! -f "$SYSOM_CONF" ]; then
        red "old $SYSOM_CONF not exist, please install sysom first .............."
        exit 1
    fi
}

subcommand=$1
case $subcommand in
"" | "-h" | "--help")
    sub_help
    ;;
*)
    ensure_supervisor_active
    check_config_exist
    shift
    sub_${subcommand} $@ | tee -a ${SYSOM_INIT_LOG} || exit 1
    if [ $? = 127 ]; then
        echo "Error: '$subcommand' is not a known subcommand." >&2
        echo "       Run '$ProgName --help' for a list of known subcommands." >&2
        exit 1
    fi
    ;;
esac
